package com.shop.controller;

import com.shop.dto.*;
import com.shop.entity.user.User;
import com.shop.exception.UserLoginFailedException;
import com.shop.service.TokenService;
import com.shop.service.UserServiceRest;
import com.shop.vo.UserTokenVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

@RestController
@RequestMapping("/user")
public class LoginUserController {
    @Autowired
    private UserServiceRest userServiceRest;
    @Autowired
    private TokenService tokenService;
    @PostMapping("loginUser")
    public Dto loginUser(String usercode, String userpassword, HttpServletRequest request) {
        if(!EmptyUtils.isEmpty(usercode) && !EmptyUtils.isEmpty(userpassword)){
            User user =null;
            user = userServiceRest.LoginUser(usercode.trim(), MD5.getMd5(userpassword.trim(), 32));
            if(EmptyUtils.isNotEmpty(user)){
                String token = tokenService.generateToken(
                        request.getHeader("user-agent"), user);
                //将token存入redis
                tokenService.save(token, user);
                //返回UserTokenVo
                UserTokenVO tokenVO = new UserTokenVO(token,
                        Calendar.getInstance().getTimeInMillis() + TokenService.SESSION_TIMEOUT * 1000,//2h有效期
                        Calendar.getInstance().getTimeInMillis());

                return DtoUtil.returnDataSuccess(tokenVO);
            }else {
                return DtoUtil.returnFail("用户名密码错误", ErrorCode.AUTH_AUTHENTICATION_FAILED);
            }
        }else {
            return DtoUtil.returnFail("参数错误！检查提交的参数名称是否正确。", ErrorCode.AUTH_PARAMETER_ERROR);
        }
    }
}
